package com.laxia.exception;

import com.laxia.model.Result;
import com.laxia.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Properties;

@Getter
@Setter
@Configuration
@AllArgsConstructor
public class ExceptionDefinitions {

    private ResourcePatternResolver resourcePatternResolver;
    private static Properties exceptionDefinitionProps;

    public Result errorResult(String message) {
        int code = Result.DEFAULT_ERROR_CODE;
        if (isErrorCode(message)) {
            code = Integer.parseInt(message);
            message = getProperty(message);
        }
        return Result.error(code, message);
    }

    public String getProperty(String errorCode) {
        return exceptionDefinitionProps.getProperty(errorCode, "系统内部错误");
    }

    public boolean isErrorCode(String value) {
        return StringUtil.isNumber(value);
    }

    @PostConstruct
    public void init() throws IOException {
        if (exceptionDefinitionProps == null) {
            Resource[] resources = resourcePatternResolver.getResources("classpath*:/props/error.properties");
            exceptionDefinitionProps = new Properties();
            Arrays.stream(resources).forEach(resource -> {
                try (InputStreamReader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
                    exceptionDefinitionProps.load(reader);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }


    }
}
